import { GATEWAY_URL } from "@/lib/env";
import Item from "@/shared/item";
import { useState, useEffect } from "react";

const useCategoryItems = (categoryId: number) => {
  const [items, setItems] = useState<Item[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchItems = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          `${GATEWAY_URL}/items/categories/${categoryId}`
        );
        const data = await response.json();
        setItems(data);
        setLoading(false);
      } catch (error) {
        console.error("Error fetching items:", error);
        setLoading(false);
      }
    };

    fetchItems();
  }, [categoryId]); // Зависимость useEffect, чтобы запрос был выполнен при изменении categoryId

  return { items, loading };
};

export default useCategoryItems;
